<template>
  <div class="mod-config">
    <el-button-group style="margin-bottom: 10px;">
      <el-button type="primary" icon="el-icon-search" @click="searchChange">查询</el-button>
      <el-button type="primary" icon="el-icon-delete" @click="searchReset">清空</el-button>
      <el-button icon="el-icon-plus" type="primary" v-if="permissions.pvm_chklight_add" @click="addOrUpdateHandle()">新增</el-button>
      <el-button icon="el-icon-plus" type="primary" v-if="permissions.pvm_chklight_add" @click="openDialog()">批量新增</el-button>
      <el-button icon="el-icon-download" type="primary" @click="getExcel()">导出成Excel</el-button>
    </el-button-group>
      <el-form inline v-show="searchShow" ref="searchForm" :model="dataForm">
				<el-row class="bg-row">
				  <el-col :span="14">
				    <el-form-item label="区域">
				      <el-form-item label-width="0">
				        <el-select v-model="dataForm.provinceCode" filterable default-first-option clearable @change="getCityOptions">
				          <el-option v-for="item in provinceOptions" :value="item.id" :label="item.regionName" :key="item.id"></el-option>
				        </el-select>
				      </el-form-item>
				      <el-form-item label-width="0">
				        <el-select v-model="dataForm.cityCode" filterable default-first-option clearable @change="getAreaOptions">
				          <el-option v-for="item in cityOptions" :value="item.id" :label="item.regionName" :key="item.id"></el-option>
				        </el-select>
				      </el-form-item>
				      <el-form-item label-width="0">
				        <el-select v-model="dataForm.areaCode" filterable default-first-option clearable>
				          <el-option v-for="item in areaOptions" :value="item.id" :label="item.regionName" :key="item.id"></el-option>
				        </el-select>
				      </el-form-item>
				    </el-form-item>
				  </el-col>
          <el-col :span="10">
            <el-form-item label="学校类型">
              <el-select v-model="dataForm.schoolType" @change="schoolTypeChangeHandle" clearable>
                <el-option v-for="item in typeOptions" :value="item.value" :label="item.label" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
				</el-row>
        <el-row class="bg-row">
          <el-col :span="14">
            <el-form-item label="学校">
              <el-form-item label-width="0">
                <el-select filterable default-first-option clearable v-model="dataForm.schoolId" @change="getGradeOption">
                  <el-option v-for="item in schoolOptions" :value="item.id" :label="item.schoolName" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="0">
                <el-select filterable default-first-option clearable v-model="dataForm.gradeId">
                  <el-option v-for="item in gradeOptions" :value="item.id" :label="item.gradeName" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="学年">
              <el-col :span="11">
                <el-date-picker style="width: 100%;" v-model="dataForm.fromYear" type="year" value-format="yyyy" placeholder="选择年"></el-date-picker>
              </el-col>
              <el-col :span="2" style="text-align: center;">至</el-col>
              <el-col :span="11">
                <el-date-picker style="width: 100%;" v-model="dataForm.toYear" type="year" value-format="yyyy" placeholder="选择年"></el-date-picker>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="bg-row">
          <el-col :span="6">
            <el-form-item label="检查日期">
              <el-date-picker v-model="dataForm.checkDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="户外参考光照度">
              <el-input v-model="dataForm.outsideLight"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="avue-crud" style="margin-top: 10px;">
        <el-table :data="dataList" border v-loading="dataListLoading">
          <el-table-column prop="checkDate" label="检查日期"></el-table-column>
          <el-table-column prop="fullName" label="班级"></el-table-column>
          <el-table-column prop="blackboardLight" label="黑板最高照度"></el-table-column>
          <el-table-column prop="lowBlackboard" label="黑板最低照度"></el-table-column>
          <el-table-column prop="averageBlackboard" label="均匀度"></el-table-column>
          <el-table-column prop="deskLight" label="课桌照度值"></el-table-column>
          <el-table-column prop="lightBad" label="灯管损坏量"></el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" v-if="permissions.pvm_chklight_edit" icon="el-icon-edit" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
              <el-button type="text" v-if="permissions.pvm_chklight_del" icon="el-icon-delete" @click="deleteHandle(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="avue-crud__pagination">
        <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" background layout="total, sizes, prev, pager, next">
        </el-pagination>
      </div>
      <!-- 弹窗, 新增 / 修改 -->
      <table-form v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></table-form>
      <!-- 弹窗, 批量新增 -->
      <batch-form v-if="batchVisible" ref="batchDialog" @refreshDataList="getDataList"></batch-form>
  </div>
</template>

<script>
  import { filterParams } from '@/util/tools'
  import { fetchList, delObj,getExcel } from '@/api/pvm/chkLight'

  import { mapGetters } from 'vuex'

  import { remote } from '@/api/admin/dict'
  import { getListByParentId } from '@/api/admin/region'
  import { fetchSchoolList } from '@/api/pvm/school'

  import { lightLingFetchList, lightLingDelObj } from '@/api/pvm/prevention/lighting'
  import { getSchoolListBySchoolType, getClassOptions } from '@/api/pvm/school'
  import { getGradeBySchoolId } from '@/api/pvm/grade'

  import TableForm from './lightIng-form'
  import BatchForm from './batch-form'

  export default {
    data() {
      return {
        provinceOptions: [],
        cityOptions: [],
        areaOptions: [],
        typeOptions: [],
        schoolOptions: [],
        gradeOptions: [],
        dataForm: {
          provinceCode: '',
          cityCode: '',
          areaCode: '',
          schoolType: '',
          schoolId: '',
          gradeId: '',
          classId: '',
          studentName: '',
          checkDate: ''
        },
        dataList: [],
        searchShow: true,
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        addOrUpdateVisible: false,
        batchVisible: false,
        schoolVisible: false,
        gradeVisible: false,
        classVisible: false
      }
    },
    components: {
      TableForm,
      BatchForm
    },
    created() {
      this.getNowDate()
      this.getDataList()
      this.getProvinceOptions()
      this.getTypeOptions()
      this.getSchoolOptions()
    },
    computed: {
      ...mapGetters(['permissions'])
    },
    methods: {
      getNowDate(){
        var d = new Date()
        let year = d.getFullYear()
        let month = d.getMonth() + 1
        let day = d.getDate()
        let str = year + '-' + ((month < 10) ? '0'+ month : month) + '-' + ((day < 10) ? '0'+ day : day)
        this.dataForm.checkDate = str

        if(month < 8){
          this.$set(this.dataForm,'fromYear',(year - 1) + '')
          this.$set(this.dataForm,'toYear', year + '')
        }else{
          // this.dataForm.formYear = year
          // this.dataForm.toYear = year + 1
        }
      },
      // 获取数据列表
      getDataList(data) {
        this.dataListLoading = true
        let params1 = {
          current: this.pageIndex,
          size: this.pageSize
        }
        if(data){
          this.$set(this.dataForm,'outsideLight',data)
        }
        let params2 = filterParams(this.dataForm)
        lightLingFetchList(Object.assign(params1,params2)).then(response => {
          if(response.data.code == '0'){
            this.dataList = response.data.data.records
            this.totalPage = response.data.data.total
          }else{
            this.$message.error(response.data.msg)
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 新增 / 修改
      addOrUpdateHandle(id) {
        if(!this.dataForm.schoolId && !id){
          this.$message.warning('请选择学校信息')
          return false
        }
        if(!this.dataForm.gradeId && !id){
          this.$message.warning('请选择年级信息')
          return false
        }
        let schoolData = {
          schoolId: this.dataForm.schoolId,
          gradeId: this.dataForm.gradeId
        }
        let form = {
          fromYear: this.dataForm.fromYear,
          toYear: this.dataForm.toYear,
          checkDate: this.dataForm.checkDate,
          outsideLight: this.dataForm.outsideLight
        }
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id,this.dataForm)
        })
      },
      // 删除
      deleteHandle(id) {
        this.$confirm('是否确认删除ID为' + id, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return lightLingDelObj(id)
        }).then(response => {
          if(response.data.code == '0'){
            this.$message.success('删除成功')
            this.getDataList()
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      searchChange() {
        this.pageIndex = 1;
        this.getDataList()
      },
      // 搜索清空
      searchReset() {
        for(let item in this.dataForm){
          this.dataForm[item] = ''
        }
      },
      handleSearchShow() {
        this.searchShow = !this.searchShow;
      },
      // 刷新回调
      refreshChange() {
        this.getDataList()
      },
			// 获取省级地址列表
			getProvinceOptions(){
			  var parentId = '86';
			  getListByParentId(parentId).then(response => {
			    if(response.data.code == '0'){
			      this.provinceOptions = response.data.data
			    }else{
			      this.$message.error(response.data.msg)
			    }
			  }).catch(() => {
			    alert("省级地址出错了，请联系管理员")
			  });
			},
			// 获取市级地址列表
			getCityOptions(val){
			  this.cityOptions = []
			  this.areaOptions = []
			  this.$set(this.dataForm,'cityCode','')
			  this.$set(this.dataForm,'areaCode','')
			  if(val){
			    getListByParentId(val).then(response => {
			      if(response.data.code == '0'){
			        this.cityOptions = response.data.data
			      }else{
			        this.$message.error(response.data.msg)
			      }
			    }).catch(() => {
			      alert("市级地址出错了，请联系管理员")
			    });
			  }
			},
			// 获取区/县级地址列表
			getAreaOptions(val){
			  this.areaOptions = []
			  this.$set(this.dataForm,'areaCode','')
			  if(val){
			    getListByParentId(val).then(response => {
			      if(response.data.code == '0'){
			        this.areaOptions = response.data.data
			      }else{
			        this.$message.error(response.data.msg)
			      }
			    }).catch(() => {
			      alert("市级地址出错了，请联系管理员")
			    });
			  }
			},
      // 获取学校列表
      getSchoolOptions(data){
        let schoolType = ''
        if(this.dataForm.schoolType === 0){
          schoolType = 0
        }else{
          schoolType = this.dataForm.schoolType || ''
        }
        getSchoolListBySchoolType(schoolType).then(response => {
          if(response.data.code == '0'){
            this.schoolOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 获取年级列表
      getGradeOption(schoolId){
        this.gradeOptions = []
        this.$set(this.dataForm,'gradeId','')
        getGradeBySchoolId(schoolId).then(response => {
          if(response.data.code == '0'){
            this.gradeOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      schoolTypeChangeHandle(val){
        this.schoolOptions = []
        this.gradeOptions = []
        this.$set(this.dataForm,'schoolId','')
        this.$set(this.dataForm,'gradeId','')
        this.getSchoolOptions()
      },
      getTypeOptions(){
        remote('school_type').then(response => {
          let responseData = response.data.data
          let list = []
          responseData.forEach(item => {
            list.push({label: item.label, value: item.value*1})
          })
          this.typeOptions = [...list]
        })
      },
      openDialog(){
        if(!this.dataForm.schoolId){
          this.$message.warning('请选择学校信息')
          return false
        }
        if(!this.dataForm.gradeId){
          this.$message.warning('请选择年级信息')
          return false
        }
        this.batchVisible = true
        this.$nextTick(() => {
          this.$refs.batchDialog.init(this.dataForm)
        })
      },
      getSchoolData(val){
        this.$set(this.dataForm,'schoolId',val.id)
        this.$set(this.dataForm,'schoolName',val.schoolName)
        this.$set(this.dataForm,'schoolType',val.schoolType)
      },
      getGradeData(val){
        this.$set(this.dataForm,'gradeId',val.id)
        this.$set(this.dataForm,'gradeName',val.gradeName)
      },
      getClassData(val){
        this.$set(this.dataForm,'classId',val.id)
        this.$set(this.dataForm,'className',val.className)
      },
       getExcel(){
            let params2 = filterParams(this.dataForm)
            getExcel(params2).then(response => {
                var blob = new Blob([response.data], {
                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                });
                var reader = new FileReader();
                reader.readAsDataURL(blob);
                reader.onload = function(e) {
                    var a = document.createElement('a');
                    a.download = "灯光监测信息.xlsx";
                    a.href = URL.createObjectURL(blob);
                    a.click();
                }
            })
        }
    }
  }
</script>

<style lang="scss" scoped>
  /deep/ .el-col {
    margin-bottom: 0 !important;
  }
  /deep/ .el-input__prefix {
    display: none!important;
  }
  .text-left {
    text-align: left!important;
  }
  .miui-table {
    width: 100%;
    margin: 10px 0;
    background-color: #b1e2ec3b;
    tr th {
      background-color: #f4f5f7;
    }

    tr th, tr td {
      padding: 10px 8px;
      border: solid 1px #fff;
      text-align: center;
    }
    .miui-table-header td{
      background-color: #7898a8;
      color: #fff;
    }
    .miui-table-tbody{
      background-color: #cadee8;
    }
    .miui-table-label {
      width: 80px;
      background-color: #b2d5f6;
    }

  }
</style>
